class h_studio {

	constructor() {
		this.oauth = {
			clientId: null,
			clientSecret: null
		}
	}

	async allow(user, ...userTypes) {
		if(!user || !user.data || userTypes.indexOf(user.data.userType) == -1)
			return this.reject('-3067', `studio user no access request interface`)
	}

	//检查工作室人员登录状态
	async checkLogin(session) {
		if(/([a-f\d]{8}(-[a-f\d]{4}){3}-[a-f\d]{12}?)/i.test(session)) {
			const user = await this.redis.session.get(session, true)
			console.log(user)
			if(user && user.type && user.userId && user.token && user.data) {
				const data = await this.redis.user.get(`studio@${user.userId}`, true)
				if(!data)
					return this.reject('-1004', `request interface permission denied`)
				const {userId, userType, userName, userSex} = data
				return this.resolve({
					userId,
					userType,
					userName,
					userSex
				})
			}
			else
				return this.reject('-2000', 'user not logined in')
		}
		else
			return this.reject('-1011', 'user type or session invalid')
	}

	async checkAccessToken(session) {
		this._updateOAuthData()
		const sessionData = await this.redis.session.get(session, true)
		if(!sessionData.data.OAuth)
			return this.reject('-3056', 'studio user login interface error')
		let {accessToken, refreshToken, expires, scope, tokenType, tokenTime} = sessionData.data.OAuth
		if(tokenTime + expires < this.common.timestamp()) {
			console.error('access_token is expired')
			const result = await this.common.reqPost({
				url: `${this.config.studio.oauth.url}authorizationserver/oauth/token`,
				headers: {
					'content-type': 'application/x-www-form-urlencoded',
					charset: 'UTF-8'
				},
				data: {
					grant_type: 'refresh_token',
					refresh_token: refreshToken,
					client_id: this.oauth.clientId,
					client_secret: this.oauth.clientSecret
				},
				getStatus: true
			})
			const {status, data} = result
			console.log(status, data)
			if(status.code != 200)
				return this.reject('-3057', 'studio user oauth refresh failed')
			tokenType = data.token_type
			accessToken = data.access_token
			refreshToken = data.refresh_token
			expires = data.expires_in
			scope = data.scope
			await this.common.updateSessionData(session, {
				OAuth: {
					tokenType,
					accessToken,
					refreshToken,
					expires,
					scope,
					tokenTime: this.common.timestamp()
				}
			}, this.config.frame.sessionExpires.studioUser)
			console.log('access_token update complete')
		}
		else
			console.log('access_token is not expired')
		return {
			accessToken,
			scope,
			tokenType
		}
	}

	//工作室人员登录
	async login({ userId, userPwd }) {
		this._updateOAuthData()
		const authResult = await this.common.reqPost({
			url: `${this.config.studio.oauth.url}authorizationserver/oauth/token`,
			headers: {
				'content-type': 'application/x-www-form-urlencoded',
				charset: 'UTF-8'
			},
			data: {
				grant_type: 'password',
				username: userId,
				password: userPwd,
				scope: 'all',
				client_id: this.oauth.clientId,
				client_secret: this.oauth.clientSecret,
				
			},
			getStatus: true
		})
		const {status: authStatus, data: authData} = authResult
		console.log(authStatus, authData)
		await this._checkInterfaceResult(authData, false)
		if(authStatus.code != 200)
			return this.reject('-3056', 'studio user oauth failed')
		const {
			token_type: tokenType,
			access_token: accessToken,
			refresh_token: refreshToken,
			expires_in: expires,
			scope
		} = authData
		const userData = await this._getUserData(userId, accessToken)
		let sessionData = {
			userType: userData.userType,
			userId: userData.userId,
			userName: userData.userName,
			OAuth: {
				tokenType,
				tokenTime: this.common.timestamp(),
				accessToken,
				refreshToken,
				expires,
				scope
			}
		}
		//保存登录态到本服务
		const {session, token} = await this.hd.user.createSession('studio', userData.userId, sessionData, this.config.frame.sessionExpires.studioUser)
		return {
			session,
			token,
			userData: {
				userId: userData.userId,
				userType: userData.userType,
				userName: userData.userName,
				userSex: userData.userSex,
				userSignDuration: userData.userSignDuration,
				userScore: userData.userScore
			}
		}
	}

	//创新盒子授权登录
	async authLogin(userType, userData) {
		switch(userType) {
			case 'student':
				const { stuId } = userData
				if(!await this._checkMemberExists(stuId))
					return this.reject('-2109', 'studio user not found, login not allowed')
				return await this.login({
					userId: stuId,
					userPwd: 'helloworld'
				})
			default:
				return this.reject('-2106', 'user type does not support auth login')
		}
	}

	//工作室人员登出
	async logout(userId, session) {
		await this.redis.session.delete(`studio@${userId}`)
		const sessionData = await this.redis.session.get(session, true)
		if(!sessionData) 
			return 1
		await this.redis.session.delete(session)
		if(!sessionData.data || !sessionData.data.OAuth)
			return 1
		const {accessToken} = sessionData.data.OAuth
		//清除认证服务器token
		const result = await this.common.reqGet({
			url: `${this.config.studio.oauth.url}authorizationserver/logout`,
			headers: {
				'content-type': 'application/x-www-form-urlencoded',
				charset: 'UTF-8'
			},
			data: {
				token: accessToken
			},
			getStatus: true
		})
		console.log(result)
		return 1
	}

	//获取首页公共数据缓存
	async getHomeDataCache() {
		return await this.redis.system.get('studioCommonData', true)
	}

	//获取首页公共数据
	async getHomeData() {
		// const result = await this.common.reqGet({
		// 	url: `${this.config.studio.url}manage/common/home`,
		// 	getStatus: true
		// })
		// const {status, data} = result
		// console.log(status, data)
		// if(status.code != 200)
		// 	return this.reject('-3060', 'studio common data interface error')
		let signRankList = await this._getSignRankingCache(0, 8)
		if(!signRankList)
			signRankList = await this._getSignRanking(0, 8)
		const data = {
			noticeList: [
				{
					id: '1001',
					content: '微科创小程序上线啦~',
					date: 1537431155
				}
			],
			problemList: [
				{
					id: '123233211312321',
					title: '给文本前面加ul一样的实心圆点',
					content: '想给小程序的文本前面 加ul一样的实心圆点 但小程序又不能用ul 各位大佬们求解 谢谢。',
					date: 1537432344
				},
				{
					id: '123233211312322',
					title: '调试时，sources下的console标签被关掉了，怎么弄回来',
					content: '调试界面原来sources下面会默认打开console，但是我手贱不小心点了个关闭，现在每次断点查log都要来回切换这两个标签，请问怎么把这个弄回来？',
					date: 1537432358
				},
				{
					id: '123233211312323',
					title: 'textarea无法动态改变文字粗细？',
					content: 'textarea无法动态改变文字粗细？是这样的，textarea动态设置了一个样式class="fb500" 也就是.fb500{ font-weight: 500;}设置完之后清除这个样式名  fb500，此时控制台看到已经是 class=""，但是，textarea中的内容仍然是粗体。。。。。。',
					date: 1537432371
				},
				{
					id: '123233211312324',
					title: '开发者工具的测试报告一直无法生成',
					content: '开发者工具的测试报告一直无法生成，已经过了24小时了，现在显示测试超时，请示怎么解决？如下图',
					date: 1537432382
				}
			],
			signRankList,
			scoreRankList: await this._getScoreRanking(0, 8)
		}
		data.signDeviceList = await this._getDeviceList()
		await this.redis.system.set('studioCommonData', data, this.config.frame.sessionExpires.studioCommonData)
		return data
	}

	//提交申请表
	async submitApply({userId, userName, userSex, userClass, userEmail, userWechat, userPhone, userMajor, userPhoto, userIntroduce}) {
		const result = await this.common.reqPost({
			url: `${this.config.studio.url}manage/application-form/`,
			data: {
				studentId: userId,
				name: userName,
				gender: userSex,
				className: userClass,
				email: userEmail,
				wechat: userWechat,
				phoneNumber: userPhone,
				major: userMajor,
				introduce: userIntroduce,
				portrait: userPhoto
			},
			getStatus: true
		})
		const {status, data} = result
		console.log(status, data)
		await this._checkInterfaceResult(data)
		if(status.code != 200)
			return this.reject('-3059', 'studio submit apply interface error')
		return 1
	}

	//检查工作室人员签到状态
	async checkSignStatus(userId) {
		let signInData = await this._checkSignStatus(userId)
		let date = new Date()
		date.setHours(0)
		date.setMinutes(0)
		date.setSeconds(0)
		//计算当日总时长
		const result = await this.mysql.cxxyStudio.execute({
			sql: 'select ifnull(sum(o.signDuration), 0) as signDuration from sign_in_record i inner join sign_out_record o on i.signId=o.signId where i.signTime > $todayTime and i.signUser=$signUser',
			data: {
				todayTime: parseInt(date.getTime() / 1000),
				signUser: userId
			}
		})
		if(!signInData && result[0]) {
			return {
				signDuration: parseInt(result[0].signDuration)
			}
			return signInData
		}
		else if(result[0]) {
			signInData.signDuration = parseInt(result[0].signDuration)
			return signInData
		}
		else {
			return {
				signDuration: 0
			}
		}
	}

	//工作室人员签到
	async signIn(userId, userName, deviceId) {
		await this._checkSignDeviceOpen(deviceId)
		const signInData = await this._checkSignStatus(userId)
		if(signInData)
			return this.reject('-3062', 'user is signed')
		const nowTime = this.common.timestamp()
		const signId = await this.common.createRandomStr(10)
		await this.mysql.cxxyStudio.insert({
			table: 'sign_in_record',
			field: [
				'signId',
				'signUser',
				'signUserName',
				'signDeviceId',
				'signTime'
			],
			data: {
				signId,
				signUser: userId,
				signUserName: userName,
				signDeviceId: deviceId,
				signTime: nowTime
			}
		})
		await this._clearSignRecordCache(userId)
		return {
			signId,
			signTime: nowTime,
			serverTime: this.common.timestamp()
		}
	}

	//工作室人员签退
	async signOut(signId, userId, deviceId) {
		await this._checkSignDeviceOpen(deviceId)
		const signInData = await this._checkSignStatus(userId)
		if(!signInData)
			return this.reject('-3063', 'user not sign in, sign out failed')
		let userData = await this.redis.user.get(`studio@${userId}`, true)
		const nowTime = this.common.timestamp()
		const signDuration = nowTime - signInData.signTime
		await this.mysql.cxxyStudio.insert({
			table: 'sign_out_record',
			field: [
				'signId',
				'signDuration',
				'signDeviceId',
				'signTime'
			],
			data: {
				signId,
				signDuration,
				signDeviceId: deviceId,
				signTime: nowTime
			}
		})
		if(userData && userData.userSignDuration) {
			userData.userSignDuration = parseInt(userData.userSignDuration) + parseInt(signDuration)
			await this.redis.user.set(`studio@${userId}`, userData, this.config.frame.sessionExpires.studioUser)
		}
		await this._clearSignRecordCache(userId)
		return {
			signTime: nowTime,
			signDuration
		}
	}

	//获取签到记录缓存
	async getSignRecordCache(userId) {
		return await this.redis.cache.get(`signRecord@${userId}`, true)
	}

	//获取签到记录
	async getSignRecord(userId) {
		let date = new Date()
		date.setHours(0)
		date.setMinutes(0)
		date.setSeconds(0)
		const todayTime = parseInt(date.getTime() / 1000)
		const yesterdayTime = todayTime - 86400
		const result = await this.mysql.cxxyStudio.execute({
			sql: 'select i.signId, i.signTime as signInTime, o.signTime as signOutTime, signDuration from sign_in_record i inner join sign_out_record o on i.signId=o.signId where i.signTime > $yesterdayTime and o.signTime > $yesterdayTime and i.signUser=$signUser',
			data: {
				yesterdayTime,
				signUser: userId
			},
			sort: {
				field: 'i.signTime',
				order: 'desc'
			}
		})
		let todaySignRecordList = []
		let yesterdaySignRecordList = []
		for(let {signId, signInTime, signOutTime, signDuration} of result) {
			if(signInTime < todayTime) {
				yesterdaySignRecordList.push({
					signId,
					signStatus: 0,
					signTime: signInTime
				})
				yesterdaySignRecordList.push({
					signId,
					signStatus: 1,
					signDuration,
					signTime: signOutTime
				})
			}
			else {
				todaySignRecordList.push({
					signId,
					signStatus: 0,
					signTime: signInTime
				})
				todaySignRecordList.push({
					signId,
					signStatus: 1,
					signDuration,
					signTime: signOutTime
				})
			}
		}
		todaySignRecordList = todaySignRecordList.sort((a, b) => {
			return b.signTime - a.signTime
		})
		yesterdaySignRecordList = yesterdaySignRecordList.sort((a, b) => {
			return b.signTime - a.signTime
		})
		const signRecord = {
			todaySignRecordList,
			yesterdaySignRecordList
		}
		await this.redis.cache.set(`signRecord@${userId}`, signRecord, this.config.frame.sessionExpires.studioSignRecord)
		return signRecord
	}

	async addFeedback(userId, content, contact) {
		if(!userId)
			return this.reject('-2034', 'feedback user id invalid')
		if(!content || content.length > 255)
			return this.reject('-2032', 'feedback content length invalid')
		if(!contact || contact.length > 120)
			return this.reject('-2032', 'feedback contact length invalid')
		const feedbackId = await this.common.createRandomStr(10)
		const result = await this.mysql.cxxyStudio.select({
			table: 'feedback',
			field: 'feedbackId',
			where: 'feedbackId=$feedbackId',
			data: {
				feedbackId
			}
		})
		if(result[0])
			return this.reject('-2035', 'feedback is exists')
		await this.mysql.cxxyStudio.insert({
			table: 'feedback',
			field: [
				'feedbackId',
				'feedbackUser',
				'feedbackContent',
				'feedbackContact',
				'feedbackDate'
			],
			data: {
				feedbackId,
				feedbackUser: userId,
				feedbackContent: content,
				feedbackContact: contact,
				feedbackDate: parseInt(Date.now() / 1000)
			}
		})
		return feedbackId
	}

	async getUserDataCache(userId) {
		return await this._getUserDataCache(userId)
	}

	async getUserData(userId, accessToken) {
		return await this._getUserData(userId, accessToken)
	}

	async getOSSToken() {
		const result = await this.common.reqGet({
			url: `${this.config.studio.url}manage/ossToken/`,
			getStatus: true
		})
		const {status, data} = result
		await this._checkInterfaceResult(data)
		if(status.code != 200)
			return this.reject('-3069', 'studio get oss token failed')
		return data.data
	}

	async getSignRankingCache(...params) {
		return await this._getSignRankingCache(...params)
	}

	async getSignRanking(...params) {
		return await this._getSignRanking(...params)
	}

	checkDeviceId(deviceId) {
		return /([a-f\d]{8}(-[a-f\d]{4}){3}-[a-f\d]{12}?)/i.test(deviceId)
	}

	async _getSignRankingCache(current = 0, count = 10, sort = 'desc') {
		return await this.redis.cache.get(`signRanking@${current}/${count}@${sort}`, true)
	}

	async _getSignRanking(current = 0, count = 10, sort = 'desc') {
		const signRanking = await this.mysql.cxxyStudio.execute({
			sql: `select i.signUser as userId, i.signUserName as userName, sum(signDuration) as userSignDuration from sign_out_record o inner join sign_in_record i on o.signId=i.signId group by i.signUser order by userSignDuration ${sort == 'asc' ? 'asc' : 'desc'} limit $start,$end`,
			data: {
				start: current * count,
				end: parseInt(count)
			},
			decrypt: 'userName'
		})
		//获得今天凌晨时间点
		let date = new Date()
		date.setHours(0)
		date.setMinutes(0)
		date.setSeconds(0)
		//使用今天时间总秒数减去今日已过去的时间，得到接下来的排行榜缓存有效时长
		const expireTime = 86400 - parseInt((Date.now() - date.getTime()) / 1000)
		await this.redis.cache.set(`signRanking@${current}/${count}@${sort}`, signRanking, expireTime)
		return signRanking
	}

	async getScoreRankingCache(...params) {
		return await this._getScoreRankingCache(...params)
	}

	async getScoreRanking(...params) {
		return await this._getScoreRanking(...params)
	}

	async getUserSignDuration(userId) {
		return await this._getUserSignDuration(userId)
	}

	async checkSignOpenStatus(signType) {
		const {signInOpen, signOutOpen, signStartTime, signEndTime} = await this._getCommonData(['signInOpen', 'signOutOpen'][signType], 'signStartTime', 'signEndTime')
		console.log('数据', [signInOpen, signOutOpen][signType])
		if(!([signInOpen, signOutOpen][signType]))
			return this.reject('-3074', `currently banned sign-${['in', 'out'][signType]}`)
		if(!/^\d+:\d+$/.test(signStartTime) || !/^\d+:\d+$/.test(signEndTime))
			return this.reject('-3077', 'sign allow time invalid')
		const date = new Date()
		const nowHours = date.getHours()
		const nowMinutes = date.getMinutes()
		const [startHours, startMinutes] = signStartTime.split(':')
		const [endHours, endMinutes] = signEndTime.split(':')
		if(nowHours < startHours || nowHours > endHours || (nowHours == startHours ? nowMinutes < startMinutes : false) || (nowHours == endHours ? nowMinutes > endMinutes : false))
			return this.reject('-3073', 'now time not allow sign')
	}

	async getCommonData(...fields) {
		return await this._getCommonData(...fields)
	}

	async _getCommonData(...fields) {
		let commonData = await this.redis.system.get('studioCommonData', true)
		if(!commonData) {
			commonData = await this.mysql.cxxyStudio.select({
				table: 'common',
				field: ['infoName', 'infoValue'],
				where: `infoName in ('${fields.join(`','`)}')`
			})
			let temp = {}
			for(let data of commonData) {
				temp[data.infoName] = data.infoValue
			}
			commonData = temp
			await this.redis.system.set('studioCommonData', commonData)
		}
		else {
			const keys = Object.keys(commonData)
			const noFields = fields.filter((key) => {
				return keys.indexOf(this.common.trim(key)) == -1
			})
			if(noFields.length != 0) {
				let result = await this.mysql.cxxyStudio.select({
					table: 'common',
					field: ['infoName', 'infoValue'],
					where: `infoName in ('${noFields.join(`','`)}')`
				})
				if(result[0]) {
					let temp = {}
					for(let data of result) {
						temp[data.infoName] = data.infoValue
					}
					Object.assign(commonData, temp)
				}
				await this.redis.system.set('studioCommonData', commonData)
			}
		}
		let data = {}
		for(let k of fields) {
			const temp = this.common.isJson(commonData[k])
			data[k] = temp ? temp : commonData[k]
		}
		commonData = data
		return commonData ? commonData : null
	}

	async _checkSignDeviceOpen(deviceId) {
		const result = await this.mysql.cxxyStudio.select({
			table: 'sign_device',
			field: 'deviceBroken',
			where: 'deviceId=$deviceId',
			data: {
				deviceId
			}
		})
		if(!result[0])
			return this.reject('-3078', 'device not found')
		if(result[0].deviceBroken)
			return this.reject('-3079', 'device is broken')
	}

	async _getScoreRankingCache(current = 0, count = 10, sort = 'desc') {
		return await this.redis.cache.get(`scoreRanking@${current}/${count}@${sort}`, true)
	}

	async _getScoreRanking(current = 0, count = 10, sort = 'desc') {
		const result = await this.common.reqGet({
			url: `${this.config.studio.url}manage/event-records/rankingList/`,
			data: {
				current: current - 1,
				order: sort == 'desc' ? 1 : -1,
				size: count
			},
			getStatus: true
		})
		const {status, data} = result
		console.log(status, data)
		await this._checkInterfaceResult(data)
		if(status.code != 200)
			return this.reject('-3070', 'get studio user score failed')
		let rankingData = []
		for(let record of data.data.records)
			rankingData.push({
				userId: record.studentId,
				userName: record.studentName,
				userScore: record.totalScore
			})
		//获得今天凌晨时间点
		let date = new Date()
		date.setHours(0)
		date.setMinutes(0)
		date.setSeconds(0)
		//使用今天时间总秒数减去今日已过去的时间，得到接下来的排行榜缓存有效时长
		const expireTime = 86400 - parseInt((Date.now() - date.getTime()) / 1000)
		await this.redis.cache.set(`scoreRanking@${current}/${count}@${sort}`, rankingData, expireTime)
		return rankingData
	}

	async _checkMemberExists(stuId) {
		const result = await this.common.reqGet({
			url: `${this.config.studio.url}manage/users/has/${stuId}`,
			getStatus: true
		})
		const {status, data} = result
		await this._checkInterfaceResult(data)
		if(status.code != 200)
			return this.reject('-2108', 'check studio user exists failed')
		return Boolean(data.data)
	}

	async _clearSignRecordCache(userId) {
		await this.redis.cache.delete(`signRecord@${userId}`)
	}

	async _getUserDataCache(userId) {
		return await this.redis.user.get(`studio@${userId}`, true)
	}

	async _getUserData(userId, accessToken) {
		const result = await this.common.reqGet({
			url: `${this.config.studio.url}manage/students/${userId}`,
			data: {
				access_token: accessToken
			},
			getStatus: true
		})
		const {status, data} = result
		console.log(status, data)
		await this._checkInterfaceResult(data)
		if(status.code != 200)
			return this.reject('-3064', 'get studio user data failed')
		const {
			level,
			//学号（用户ID） 1601170130
			studentId,
			//名字 陈炜宾
			name,
			//班级名称 16软件1班
			className,
			//年级 2016
			grade,
			//邮箱
			email,
			//微信号
			wechat,
			//性别 0 未知 1 男 2 女
			gender,
			//籍贯 广东汕尾
			nativePlace,
			//身份证号码
			identity,
			//qq号码
			qq,
			//博客链接
			blogUrl,
			//专业方向
			major,
			//手机号码
			phoneNumber
		} = data.data
		console.log(data.data)
		const userData = {
			userType: parseInt(level),
			userId: studentId,
			userName: name,
			userSex: gender,
			userGrade: grade,
			userClass: className,
			userEmail: email,
			userNativePlace: nativePlace,
			userIdentity: identity,
			userQQ: qq,
			userWechat: wechat,
			userBlog: blogUrl,
			userMajor: major,
			userPhone: phoneNumber,
			userScore: await this._getUserScore(userId, accessToken),
			userSignDuration: await this._getUserSignDuration(userId)
		}
		await this.redis.user.set(`studio@${userId}`, userData, this.config.frame.sessionExpires.studioUser)
		return userData
	}

	async _checkInterfaceResult(result, checkFormat = true) {
		if(!result.status && checkFormat)
			return this.reject('-3065', 'studio interface return data is bad format')
		if(result.status == 'failed') {
			const errData = this.config.studio.errList[`${result.code}`]
			if(!errData)
				return this.reject('-3068', 'studio interface unknown error')
			return this.reject(errData.code, errData.msg)
		}
		return true
	}

	async _getUserSignCount(userId) {
		const result = await this.mysql.cxxyStudio.execute({
			sql: 'select ifnull(sum(o.signDuration), 0) as signDuration from sign_in_record i inner join sign_out_record o on i.signId=o.signId where i.signTime > $todayTime and i.signUser=$signUser',
			data: {
				signUser: userId
			}
		})
	}

	async _updateOAuthData() {
		this.oauth.clientId = this.oauth.clientId || this.crypto.decryptDataKey(this.config.studio.oauth.clientId)
		this.oauth.clientSecret = this.oauth.clientSecret || this.crypto.decryptDataKey(this.config.studio.oauth.clientSecret)
	}

	//检查工作室人员签到状态
	async _checkSignStatus(userId) {
		let date = new Date()
		date.setHours(0)
		date.setMinutes(0)
		date.setSeconds(0)
		const signInResult = await this.mysql.cxxyStudio.select({
			table: 'sign_in_record',
			field: [
				'signId',
				'signUser',
				'signTime'
			],
			data: {
				todayTime: parseInt(date.getTime() / 1000),
				signUser: userId
			},
			where: 'signTime > $todayTime && signUser=$signUser',
			sort: {
				field: 'signTime',
				order: 'desc'
			}
		})
		if(!signInResult[0])
			return null
		const {signId, signTime, signUser} = signInResult[0]
		const signOutResult = await this.mysql.cxxyStudio.select({
			table: 'sign_out_record',
			field: [
				'signTime'
			],
			data: {
				todayTime: parseInt(date.getTime() / 1000),
				signId
			},
			where: 'signTime > $todayTime && signId=$signId'
		})
		if(signOutResult[0])
			return null
		else {
			let signInData = signInResult[0]
			signInData.serverTime = this.common.timestamp()
			return signInData
		}
	}

	//获取签到基站列表
	async _getDeviceList() {
		const deviceList = await this.mysql.cxxyStudio.select({
			table: 'sign_device',
			field: [
				'deviceId',
				'deviceDescription'
			],
			where: 'deviceBroken=0'
		})
		return deviceList
	}

	//获取个人签到时长
	async _getUserSignDuration(userId, startTime, endTime) {
		startTime = startTime || 1535731200
		endTime = endTime || this.common.timestamp()
		const result = await this.mysql.cxxyStudio.execute({
			sql: 'select sum(signDuration) as signDuration from sign_in_record i inner join sign_out_record o on i.signId=o.signId where i.signUser=$userId and o.signTime>$startTime and o.signTime<$endTime',
			data: {
				userId,
				startTime,
				endTime
			}
		})
		if(!result[0])
			return 0
		return parseInt(result[0].signDuration)
	}

	//获取个人总积分
	async _getUserScore(userId, accessToken) {
		const result = await this.common.reqGet({
			url: `${this.config.studio.url}manage/event-records/totalScore/${userId}`,
			data: {
				access_token: accessToken
			},
			getStatus: true
		})
		const {status, data} = result
		await this._checkInterfaceResult(data)
		if(status.code != 200)
			return this.reject('-3070', 'get studio user score failed')
		return parseInt(data.data.score)
	}

}

module.exports = h_studio